using DmServer.Handlers;

namespace DmServer;

public class ServerHelper
{
    private TcpService? service = null;
    private MessageHandlerManager? manager;

    public ServerHelper()
    {
        Console.CancelKeyPress += OnExit;
        AppDomain.CurrentDomain.ProcessExit += OnExit;
    }

    public void Start()
    {
        var register = RegisterDmSoft.RegisterDmSoftDll();// 免注册调用大漠插件

        manager = new MessageHandlerManager(register);

        service = new TcpService();

        //有客户端成功连接
        service.Connected = (client, e) =>
        {
            manager.Connected(client, e);
            return EasyTask.CompletedTask;
        };
        //有客户端断开连接
        service.Closed = (client, e) =>
        {
            manager.Disconnected(client, e);
            return EasyTask.CompletedTask;
        };

        //从客户端收到信息
        service.Received = (TcpSessionClient client, ReceivedDataEventArgs e) =>
        {
            manager.Received(client, e);
            return EasyTask.CompletedTask;
        };

        var config = new TouchSocketConfig()
            .SetListenIPHosts(17789)
            .SetTcpDataHandlingAdapter(() => new FixedHeaderPackageAdapter())
            .SetSendTimeout(20000)
            .ConfigureContainer(a =>
            {
                a.AddConsoleLogger();
            })
            .ConfigurePlugins(a =>
            {
                //a.UseReconnection(-1, true, 1000);
            });

        service.SetupAsync(config);
        service.StartAsync();

        service.Logger.Info("启动完成，如需要退出请按q");
        while (Console.ReadKey().KeyChar != 'q')
        {
            Console.WriteLine();
        }
    }

    public void Stop()
    {
        if (service != null)
            service.StopAsync();
    }

    private void OnExit(object? sender, ConsoleCancelEventArgs e)
    {
        if (service != null)
            service.StopAsync();
    }

    private void OnExit(object? sender, EventArgs e)
    {
        if (service != null)
            service.StopAsync();
    }
}
